﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Pikapika.Models;
using Pikapika.Models.ViewModels.Annotation;

namespace Pikapika.Controllers
{
    public class AnnotationController : Controller
    {

        public ActionResult List(int id)
        {
            if (id < 1)
            {
                return HttpNotFound();
            }
            using (var ctx = new PikapikaDBEntities())
            {
                return Json((from a in ctx.Annotations
                             where a.ChapterId == id
                             select new { a.Id, 
                                          a.AnnotationContent, 
                                          a.Position, 
                                          Rating = a.PlusRatings - a.MinusRatings })
                            .ToList(), JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult Add(AnnotationAddModel m)
        {
            if (!ModelState.IsValid)
            {
                return new HttpStatusCodeResult(400, "Bad Request");
            }
            using (var ctx = new PikapikaDBEntities())
            {
                Annotation newAnnotation = new Annotation
                                {
                                    ChapterId = m.ChapterId,
                                    Position = m.Position,
                                    AnnotationContent = m.Content
                                };
                ctx.AddToAnnotations(newAnnotation);
                try
                {
                    ctx.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
                }
                catch (Exception)
                {
#if DEBUG
                    throw;
#else
                    return new HttpStatusCodeResult(400, "Bad Request");
#endif
                }
                return Content(newAnnotation.Id.ToString());
            }
        }
    }
}
